if (typeof jQuery === "undefined") {
  throw new Error("App requires jQuery");
}

$.App = {};
$.App.Page = {};

$.App.getMainContent = function() {
    return  $("#main-content");
}

$.App.reload = function() {
    $(window).trigger("hashchange");
};

$.App.goPage = function(hash) {
    if (hash == location.hash) {
        $(window).trigger("hashchange");
    } else {
        location.hash = hash;
    }
};

$.App.initPage = function(){
    var url = location.hash.slice(1) || '/dashboard';
    $.ajax(url, {
        success: function(data) {
            $.App.getMainContent().html(data);
        },
        statusCode: {
            403: function() {
                var html = template('error-403', {});
                $.App.getMainContent().html(html);
            },
            404: function() {
                var html = template('error-404', {});
                $.App.getMainContent().html(html);
            },
            500: function() {
                var html = template('error-500', {});
                $.App.getMainContent().html(html);
            }
        },
        error: function() {
            $.App.getMainContent().html($("#error-500").html());
        }
    });
};

$.App.alert = function(title, content, callback) {
    var html = template('alert-tmpl', {"title": title, "content": content});
    var $modal = $(html);
    $modal.find("#btn-sure").off("click").on("click", function(){
        if (callback && typeof callback === "function") {
            callback();
        }
        $modal.modal("hide");
    });

    $modal.modal("show");
};

$.App.notify = function(message, config) {
    var defaultConfig = {
        type: 'success',
        align: 'center',
        offset: {from: 'top', amount: $(window).height()/2},
        delay: 1500
    };

    $.bootstrapGrowl(message, $.extend({}, defaultConfig, config));
};

$.App.notifyError = function(message) {
    $.App.notify(message, {type : "error"})
}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(document).ready(function() {

});